package crmdna.client.contactdetail;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import crmdna.client.group.Group;
import crmdna.common.APIException;
import crmdna.common.Utils;
import crmdna.common.APIResponse.Status;


public class ContactDetail {
	public enum Gender {
		MALE, FEMALE
	}
	
	public static class ContactDetailProp {
		public String email;
		public String firstName;
		public String lastName;
		public String homeAddress;
		public String officeAddress;
		public String homePhone;
		public String officePhone;
		public String mobilePhone;	
		public Gender gender;
		
		public long centerId;
		
		public String getName() {
			if ((firstName == null) && (lastName == null))
				return null;
			
			if (firstName == null)
				return lastName;
			
			if (lastName == null)
				return firstName;
			
			return firstName + " " + lastName;						
		}
		
		public String getPhoneNos() {
			//TODO add test case
						
			String phoneNos = "";
			if (mobilePhone != null) 
				phoneNos += mobilePhone + " ";
			
			if (officePhone != null)
				phoneNos += officePhone + " ";
			
			if (homePhone != null)
				phoneNos += homePhone;
			
			return phoneNos;			
		}
	}
			
	public static void ensureValid(String client, List<ContactDetailProp> contacts) {
		
		Set<Long> allGroupIds = Group.getAllGroupIds(client);
				
		for (int i = 0; i < contacts.size(); i++) {
			ContactDetailProp c = contacts.get(i);
			
			if ((c.firstName == null) || c.firstName.equals(""))
				throw new APIException(Status.ERROR_RESOURCE_INCORRECTLY_SPECIFIED, 
						"Error in record no [" + (i + 1) + "]: First name is missing");
			
			boolean emailOrPhoneSpecified = false;
			emailOrPhoneSpecified = emailOrPhoneSpecified || Utils.isValidEmailAddress(c.email);
			emailOrPhoneSpecified = emailOrPhoneSpecified || Utils.isValidPhoneNumber(c.mobilePhone);
			emailOrPhoneSpecified = emailOrPhoneSpecified || Utils.isValidPhoneNumber(c.homePhone);
			emailOrPhoneSpecified = emailOrPhoneSpecified || Utils.isValidPhoneNumber(c.officePhone);
			
			if (! emailOrPhoneSpecified)
				throw new APIException(Status.ERROR_RESOURCE_INCORRECTLY_SPECIFIED, 
						"Error in record no [" + (i + 1) + 
						"]: Email or atleast one contact phone number should be valid. " + 
						"Phone number should start with +. Eg: +659867364");
			
			if (! allGroupIds.contains(c.centerId)) {
				throw new APIException(Status.ERROR_RESOURCE_DOES_NOT_EXIST, 
						"Error in record no [" + (i + 1) + 
						"]: There is no center with centerId [" + c.centerId + "]");			
			}
		}
	}
	
	public static void ensureValid(String client, ContactDetailProp contact) {
		List<ContactDetailProp> contacts = new ArrayList<>();
		ensureValid(client, contacts);
	}
}
